package com.jlnx.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 数据库工具类
 * @author WYQ
 *
 */
public class DBUtils {
	public static void main(String[] args) {
		System.out.println(DBUtils.getConnection());
//		java.sql.Date date = DBUtils.getDate("2020-02-02");
//		System.out.println(date);
	}
	
	/*
	 * 连接数据库
	 */
	public static Connection getConnection() {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
//			路径
			String url = "jdbc:mysql://localhost:3306/gongyinglian?serverTimezone=UTC&characterEncoding=UTF-8";
//			用户名
			String user = "root";
//			密码
			String password = "root";
			Connection conn = DriverManager.getConnection(url, user, password);
			return conn;
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/*
	 * 关闭连接
	 */
	public static void close(Connection conn,PreparedStatement pstm) {
		try {
			pstm.close();
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void close(Connection conn,PreparedStatement pstm,ResultSet rs) {
		try {
			rs.close();
			pstm.close();
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/*
	 * 日期转换
	 */
	public static java.sql.Date getDate(String strDate) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date utilDate = sdf.parse(strDate);
			java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
			return sqlDate;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/*
	 * 将util的日期转换为sql的日期
	 */
	public static java.sql.Date changeDate(Date date) {
        long timestamp = date.getTime();
        java.sql.Date sqlDate = new java.sql.Date(timestamp);
		return sqlDate;
	}
}
